import {View, Text, Block, Image, Button} from '@tarojs/components'
import React, { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import {AtFloatLayout, AtIcon, AtModal, AtModalAction, AtModalContent, AtModalHeader} from 'taro-ui'
import {user} from "../../../utils/user.service";
import {http} from "../../../utils/http";
import {USER_SALE_SUB} from "../../../constants/api";
import './detail-bar.scss';

interface DetailBarType {
  upDataDetail?: any
  qrImgDescribe?: any
  isShowShareButton?: any
  onGetPoster?: any
  good?: any
  isLogin?: any
  surplusStock?: any
  groupDetail?: any
  notOpen?: any
  onGroupBuy?: any
  onViewMyTeam?: any
  onJoinGroup?: any
  onGotoBuy?: any
  onGotoHome?: any
  onContact?: any
  getMSG?: any
  weChat?: any
  disabled?: boolean
  status: number
  subscribe?: number
  uuid?: string
  showService?: boolean
  isOpened?: boolean
  inSale?: boolean
  isSaler: boolean
  zeroBuy?: number
  platformSet?: any
  oneMinute?: boolean
  removeMSG?: any
  orderNum?: any
  onOpenModel?: any
  commissionPrice?: any
  handleCancel?: any
  qrImg?: any
  onWXOpenModel?: any
  wxModalShow?: boolean
  showLoading?: boolean
  isLL?: number
  wxhandleCancel?: any
  groupBuyId?: any
  showWx?: any
  wxQrImg?: any
  isInStoreHouse?: any
  bdInfo?: any
}

const DetailBar: React.FC<DetailBarType> = (props) => {
  const [open, setOpen] = useState(0);
  const [bdKey, setBdKey] = useState();
  const [isLogin, setIsLogin] = useState(0);
  const [bdInfo, setBdInfo] = useState(false);
  const [isOpened, setIsOpened] = useState(props.isOpened)
  const [value, setValue] = useState(1)
  const [displayIndexTwo, setDisplayIndexTwo] = useState(0)
  const [tmplIds, setTmplIds] = useState([]);
  const [modalShow, setModalShow] = useState(false);
  useEffect(() => {
    if (props.platformSet && props.platformSet.openSaleMessageSubscribe && process.env.TARO_ENV !== 'tt') {
      setOpen(props.platformSet.openSaleMessageSubscribe)
      setTmplIds(props.platformSet.saleMessageTemplateId)
    }
  }, [props.platformSet])

  useEffect(() => {
    if (process.env.TARO_ENV === 'tt') {
      setBdKey(http.getBDKey())
    }
  }, [])

  useEffect(() => {
    if (process.env.TARO_ENV === 'tt') {
      setBdInfo(props.bdInfo)
    }
  }, [props.bdInfo])

  useEffect(() => {
    setIsLogin(props.isLogin)
  }, [props.isLogin])

  const getMSG = async () => {
    if (!isLogin) {
      await user.jumpLogin()
      return
    }
    const uuid = props.uuid
    try {
      const acceptAry = []
        [process.env.TARO_ENV === 'tt' ? 'tt' : 'TARO']['requestSubscribeMessage']({
        tmplIds,
        success(res) {
          //[tmplIds]是动态的键，即模板id，值包括'accept'、'reject'、'ban'、'filter'。'accept'表示用户同意订阅该条id对应的模板消息，'reject'表示用户拒绝订阅该条id对应的模板消息，'ban'表示已被后台封禁，'filter'表示该模板因为模板标题同名被后台过滤。例如 { errMsg: "requestSubscribeMessage:ok", zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: "accept"} 表示用户同意订阅zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE这条消息
          tmplIds.map((item, i) => {
            if (res[item] == 'accept') {
              acceptAry.push(item)
            }
          })
          if (acceptAry.length > 0) {
            http.post(USER_SALE_SUB, {goodsUUID: uuid, templateIds: acceptAry.join(",")})
            props.getMSG()
          }
        }
      })
    } catch (e) {
      Taro.showModal({
        title: '提示',
        content: '为了提供更好的服务，建议您开启订阅消息',
        success: (res) => {
          if (res.confirm) {
            Taro.openSetting()
          }
        }
      })
    }
  }
  const isShowLayOut = () => {
    if (props.groupDetail) {
      if (props.groupDetail.activity_type === 3) {
        setIsOpened(true)
      } else {
        props.onGroupBuy(0, props.groupDetail.group_price)
      }
    }
  }
  const choiceSpecsTeamTwo = (i) => {
    setDisplayIndexTwo(i)
  }
  const handleChange = (type) => {
    let val = value
    if (type) {
      if (props.surplusStock < ++val) {
        return Taro.showToast({
          title: '库存不足',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      if (--val < 1) {
        val = 1
      }
    }
    setValue(val)
  }
  const sureBtn = async () => {
    if (value == 0) {
      Taro.showToast({
        title: '购买数量不能为0',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (isLogin) {
      props.onGroupBuy(props.groupDetail.step_list[displayIndexTwo].step_num, props.groupDetail.step_list[displayIndexTwo].group_price)
    } else {
      user.jumpLogin()
    }
  }
  const showImg = (current) => {
    const url = current['images'][0]['url']
    Taro.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url]// 需要预览的图片http链接列表
    })
  }

  const goBuy = () => {
    props.onGotoBuy()
  }

  return (
    <View className='detailBar zindex limit-detailBar'>
      {!props.showLoading && <View className='service-box tt-service-box'>
        <View className='service-item goto-home' onClick={props.onGotoHome}>
          <View className='home'><AtIcon value='icon icon-shouye-01' customStyle='font-size: 20px' size='20' color='#000' /></View>
          <View className='text'>首页</View>
        </View>
        {process.env.TARO_ENV !== 'tt' && props.showService && (!props.qrImg || props.qrImg === 'variable_code_close') &&
          <View className='service-item goto-service' onClick={props.onContact}>
            <View className='kefu'><AtIcon value='icon icon-kefu-01' customStyle='font-size: 20px' size='20' color='#000' /></View>
            <View className='text'>客服</View>
          </View>}
        {process.env.TARO_ENV !== 'tt' && props.showService && (props.qrImg && props.qrImg !== 'variable_code_close') &&
          <View className='service-item goto-service' onClick={() => {
            setModalShow(true)
          }}
          >
            <View className='kefu'><AtIcon value='icon icon-kefu-01' customStyle='font-size: 20px' size='20' color='#000' /></View>
            <View className='text'>客服</View>
          </View>}
        {props.isShowShareButton && (props.groupDetail || props.notOpen) && !process.env.SHOW_SHARE_POSTER &&
          <View className={`service-item ${!props.showService && 'no-kefu'}`} onClick={props.onGetPoster}>
            <View className='kefu'>
              <AtIcon value='icon icon-fenxiang-01-01' customStyle='font-size: 20px' size='20' color='#000' />
            </View>
            {props.isSaler && <View className='text'>分享赚</View>}
            {!props.isSaler && <View className='text'>分享赚</View>}
          </View>}
        {process.env.TARO_ENV === 'tt' && <Button className='tt-button service-item goto-service' open-type='contact'>
          <View className='kefu'><AtIcon value='icon icon-kefu-01' customStyle='font-size: 20px' size='20' color='#000' /></View>
          <View className='text'>客服</View>
        </Button>}
        {process.env.TARO_ENV === 'tt' && <Button className='tt-button service-item goto-service' open-type='share'>
          <View className='kefu'><AtIcon value='icona-xingzhuangjiehe2' customStyle='font-size: 20px' prefixClass='tabpole' size='20'
            color='#000'
          /></View>
          <View className='text'>分享</View>
        </Button>}
      </View>}
      {process.env.TARO_ENV !== 'tt' && !props.showLoading && props.isShowShareButton &&
        <View className='right-btn-box'>
          {((props.isLL == 1) || ((props.inSale && (props.status === 1 || props.status === 0)) && (((props.disabled && (!props.groupDetail || props.groupDetail.is_join === 1)) || (!props.disabled && (!props.groupDetail || props.groupDetail.is_join === 1))) || props.groupDetail))) &&
            <View className='capsules'>
              {!!props.inSale && <Block>
                {process.env.SHOW_SHARE_POSTER && !props.groupDetail && <View
                  className={`get-poster-btn share ${((props.status === -1 || props.status === 99 || props.status === 0) && !open) && 'noGroupDetail'}`}
                  onClick={props.onGetPoster}
                >
                  <View className='top'>分享</View>
                  {!!props.commissionPrice && <View className='bottom'>预计赚<Text className='dollar'>￥</Text><Text
                    className='true-price'
                  >{props.commissionPrice}</Text></View>}
                </View>}
                {props.status === 1 &&
                  <Block>
                    {props.disabled &&
                      <View style={!process.env.SHOW_SHARE_POSTER ? 'border-radius: 32px !important;' : ''}
                        className={`${props.groupDetail ? 'share' : 'limited'}`} onClick={props.onGotoBuy}
                      >
                        <View
                          className='top'
                        >{props.zeroBuy != 1 ? props.groupDetail ? '单独购买' : '抢购' : '免费领取'}</View>
                        {props.groupDetail && <View className='bottom'>
                          <Text className='dollar'>￥</Text>
                          <Text className='true-price'>{props.good.price}</Text>
                        </View>}
                        {process.env.DISTINGUISH_IDENTITY && !props.groupDetail && !!props.commissionPrice &&
                          <View className='bottom'>购买返
                            <Text className='dollar'>￥</Text>
                            {props.commissionPrice && <Text className='true-price'>{props.commissionPrice}</Text>}
                          </View>}
                      </View>}
                    {!props.disabled &&
                      <View
                        style={!process.env.SHOW_SHARE_POSTER ? 'display:inline-block;border-radius: 32px !important;' : 'display:inline-block;'}
                      >
                        {props.groupDetail &&
                          <View className={`disabled ${props.groupDetail ? 'share' : 'limited'}`}>
                            <View className='top'>单独购买</View>
                            <View className='bottom'><Text className='dollar'>￥</Text><Text
                              className='true-price'
                            >{props.good.price}</Text></View>
                          </View>}
                        {!props.groupDetail &&
                          <View className={`disabled ${props.groupDetail ? 'share' : 'limited'}`}>
                            <View className='top'>{props.zeroBuy != 1 ? '抢购' : '免费领取'}</View>
                            {process.env.DISTINGUISH_IDENTITY && !!props.commissionPrice &&
                              <View className='bottom'>购买返<Text className='dollar'>￥</Text><Text
                                className='true-price'
                              >{props.commissionPrice}</Text></View>}
                          </View>}
                      </View>
                    }
                  </Block>
                }
              </Block>
              }
              <Block>
                {props.groupDetail && !!props.inSale && !(props.status === -1 || props.status === 99 || props.status === 0) &&
                  <Block>
                    {props.groupDetail.is_share === '0' && !props.groupDetail.is_join &&
                      <View className={`goto-buy-btn limited ${!props.inSale && 'noGroupDetail'}`}
                        onClick={isShowLayOut}
                      >
                        <View className='top'>立即开团</View>
                        <View className='bottom'><Text className='dollar'>￥</Text><Text
                          className='true-price'
                        >{!!props.groupDetail.discounts_price ? props.groupDetail.discounts_price : props.groupDetail.group_price}</Text></View>
                      </View>}
                    {!!props.groupDetail.is_join &&
                      <View className={`goto-buy-btn limited ${!props.inSale && 'noGroupDetail'}`}
                        onClick={props.onViewMyTeam}
                      >
                        <View className='top'>查看我的团</View>
                      </View>}
                    {props.groupDetail.is_share === '1' && !props.groupDetail.is_join && isLogin &&
                      <View className={`goto-buy-btn limited ${!props.inSale && 'noGroupDetail'}`}
                        onClick={props.onJoinGroup}
                      >
                        <View className='top'>立即参团</View>
                      </View>}
                  </Block>}
              </Block>
            </View>
          }
          {props.inSale && props.status === 0 &&
            <Block>
              {props.oneMinute ?
                <View className='capsules'>
                  <View className='end disabled limited' style='font-size: 15px !important;'>未开始</View>
                </View>
                :
                <Block>{open ?
                  <Block>
                    {(props.subscribe) ?
                      <View className='capsules'>
                        <View className='end limited noGroupDetail noGroupDetail-right' onClick={props.removeMSG}>
                          取消提醒
                        </View>
                      </View> :
                      <Block>
                        {process.env.TARO_ENV === 'h5' ? <View className='capsules'>
                          <View className='end limited noGroupDetail noGroupDetail-right disabled'>即将开售</View>
                        </View> : <View className='capsules'>
                          <View onClick={getMSG}
                            className='end limited noGroupDetail noGroupDetail-right'
                          >开售提醒</View>
                        </View>}
                      </Block>
                    }
                  </Block> :
                  <View className='capsules'><View className='end disabled limited noGroupDetail'
                    style='width: 100% !important;'
                  >未开始</View></View>}
                </Block>
              }
            </Block>
          }
          {(props.inSale && !props.groupDetail && (props.status === -1 || props.status === 99)) &&
            <View className='capsules'>
              {props.status === -1 && <View className='noGroupDetail end disabled'>已售罄</View>}
              {props.status === 99 && <View className='noGroupDetail end disabled'>已结束</View>}
            </View>
          }
          {!props.inSale && !props.groupDetail &&
            <View className='capsules'><View className='noGroupDetail end disabled'>已下架</View></View>}
        </View>}
      {process.env.TARO_ENV !== 'tt' && !props.showLoading && !props.isShowShareButton &&
        <View className='right-btn-box'>
          {((props.isLL == 1) || ((props.inSale && (props.status === 1 || props.status === 0)) && (((props.disabled && (!props.groupDetail || props.groupDetail.is_join === 1)) || (!props.disabled && (!props.groupDetail || props.groupDetail.is_join === 1))) || props.groupDetail))) &&
            <View className='isShowShareButtonFalse capsules'>
              {!!props.inSale && <Block>
                {props.status === 1 &&
                  <Block>
                    {props.disabled &&
                      <View className={`${props.groupDetail ? 'share' : ' singleLimited limited'}`}
                        onClick={props.onGotoBuy}
                      >
                        <View
                          className='top'
                        >{props.zeroBuy != 1 ? props.groupDetail ? '单独购买' : '抢购' : '免费领取'}</View>
                        {props.groupDetail && <View className='bottom'>
                          <Text className='dollar'>￥</Text>
                          <Text className='true-price'>{props.good.price}</Text>
                        </View>}
                      </View>}
                    {!props.disabled &&
                      <Block>
                        {props.groupDetail &&
                          <View className={`disabled ${props.groupDetail ? 'share' : 'limited'}`}>
                            <View className='top'>单独购买</View>
                            <View className='bottom'><Text className='dollar'>￥</Text><Text
                              className='true-price'
                            >{props.good.price}</Text></View>
                          </View>}
                        {!props.groupDetail &&
                          <View className={`disabled ${props.groupDetail ? 'share' : 'limited'}`}>
                            <View className='top'>{props.zeroBuy != 1 ? '抢购' : '免费领取'}</View>
                          </View>}
                      </Block>
                    }
                  </Block>
                }
              </Block>
              }
              <Block>
                {props.groupDetail && !!props.inSale && !(props.status === -1 || props.status === 99 || props.status === 0) &&
                  <Block>
                    {props.groupDetail.is_share === '0' && !props.groupDetail.is_join &&
                      <View className={`goto-buy-btn limited ${!props.inSale && 'noGroupDetail'}`}
                        onClick={isShowLayOut}
                      >
                        <View className='top'>立即开团</View>
                        <View className='bottom'><Text className='dollar'>￥</Text><Text
                          className='true-price'
                        >{!!props.groupDetail.discounts_price ? props.groupDetail.discounts_price : props.groupDetail.group_price}</Text></View>
                      </View>}
                    {!!props.groupDetail.is_join &&
                      <View className={`goto-buy-btn limited ${!props.inSale && 'noGroupDetail'}`}
                        onClick={props.onViewMyTeam}
                      >
                        <View className='top'>查看我的团</View>
                      </View>}
                    {props.groupDetail.is_share === '1' && !props.groupDetail.is_join && isLogin &&
                      <View className={`goto-buy-btn limited ${!props.inSale && 'noGroupDetail'}`}
                        onClick={props.onJoinGroup}
                      >
                        <View className='top'>立即参团</View>
                      </View>}
                  </Block>}
              </Block>
            </View>
          }
          {props.inSale && props.status === 0 &&
            <Block>
              {props.oneMinute ?
                <View className='capsules'>
                  <View className='end disabled limited' style='font-size: 15px !important;'>未开始</View>
                </View>
                :
                <Block>{open ?
                  <Block>{(props.subscribe) ?
                    <View className='capsules'><View className='end limited noGroupDetail noGroupDetail-right'
                      onClick={props.removeMSG}
                    >取消提醒</View></View> :
                    <Block><View className='capsules'><View onClick={getMSG}
                      className='end limited noGroupDetail noGroupDetail-right'
                    >开售提醒</View></View></Block>}</Block> :
                  <View className='capsules'><View className='end limited noGroupDetail'>未开始</View></View>}</Block>
              }
            </Block>
          }
          {(props.inSale && !props.groupDetail && (props.status === -1 || props.status === 99)) &&
            <View className='capsules'>
              {props.status === -1 && <View className='noGroupDetail end disabled'>已售罄</View>}
              {props.status === 99 && <View className='noGroupDetail end disabled'>已结束</View>}
            </View>
          }
          {!props.inSale && !props.groupDetail &&
            <View className='capsules'><View className='noGroupDetail end disabled'>已下架</View></View>}
        </View>}
      {process.env.TARO_ENV === 'tt' && !props.showLoading && bdInfo && <Block>
        {
          props.isInStoreHouse && <Block>
            {bdInfo.type === 1 && <Block>
              {!props.inSale ? <Button className='snap-up-now un-sale'>已下架</Button> : <Block>
                {props.status === 1 ? <Button className='snap-up-now' onClick={goBuy}>立即抢购</Button> : <Button
                  className='snap-up-now un-sale'
                >{props.status === -1 ? '已售罄' : props.status === 99 ? '已结束' : '即将开售'}</Button>}
              </Block>}
            </Block>}
            {bdInfo.type !== 1 && <Block>
              <zijie-pay-button
                isLogin={isLogin}
                bdKey={bdKey}
                marketingReady={false}
                mode={2}
                goodsId={props.upDataDetail.bd_spu_id}
                goods={props.upDataDetail}
              />
            </Block>}
          </Block>
        }
      </Block>}
      {isOpened &&
        <Block>
          <AtFloatLayout isOpened={isOpened} onClose={() => {
            setIsOpened(false)
          }}
          >
            <View className='choiceInfo-top'>
              {props.good && <Image className='left-img' mode='aspectFill' onClick={showImg.bind(this, props.good)}
                src={props.good['images'][0]['url'] + '?x-oss-process=image/resize,w_240'}
              />}
              <View className='right-info team-right-info'>
                <View className='price'>
                  <Block>
                    <View className='p-t-price'>
                      <View className='p-t-symbol-price'><Text
                        className='symbol'
                      >￥</Text>{props.groupDetail.step_list[displayIndexTwo].group_price}</View>
                      <View className='p-t-price-truth'>拼团价</View>
                    </View>
                  </Block>
                </View>
                {props.groupDetail && <View className='price-box-price-stock'>
                  <View className='stock'>价格 <Text className='symbol-price'><Text className='symbol'>￥</Text><Text
                    className='price'
                  >{props.good.price}</Text></Text></View>
                  <View className='stock'>剩余 {props.good.surplus_stock} 件</View>
                </View>}
              </View>
              <View className='close-btn' onClick={() => {
                setIsOpened(false)
              }}
              >
                <AtIcon value='close-circle' customStyle='font-size: 20px' size='20' color='#bfbfbf' />
              </View>
            </View>
            <View className='choiceInfo'>
              <View className='choice-specs limit-choice-specs'>
                {props.groupDetail && <View className='group-spec-list group-type-list'>
                  <View className='group-type-list choice-specs-list'>
                    {props.groupDetail && props.groupDetail['step_list'] && props.groupDetail['step_list'].length > 0 &&
                      <View>
                        <View>拼团类型</View>
                        <View className='group-spec-list'>
                          {props.groupDetail.step_list.map((items, j) => <Text
                            onClick={choiceSpecsTeamTwo.bind(this, j)}
                            className={`choice-specs-item ${displayIndexTwo === j && 'on'}`}
                            key={j}
                          >￥{items.group_price}/{items.people_num}人团</Text>)}
                        </View>
                      </View>}
                  </View>
                </View>}
              </View>
            </View>
            <View className='choice-num-box choice-num-box-limit'>
              <View className='choice-num'>
                <View className='choice-num-title'>购买数量</View>
                <View className='at-input-number car-num-small2'>
                  <View onClick={handleChange.bind(this, 0)} className='at-input-number__btn'><AtIcon value='subtract'
                    size='10' customStyle='font-size: 10px'
                  /></View>
                  <View className='at-input-number__input'>{value}</View>
                  <View onClick={handleChange.bind(this, 1)} className='at-input-number__btn'><AtIcon value='add'
                    size='10' customStyle='font-size: 10px'
                  /></View>
                </View>
              </View>
            </View>
          </AtFloatLayout>
          <View className='detailBar othercar group-sureBtn' style='background:#fff;'>
            <View className='product-btn-box btn-box'>
              <View className='limit-group-btn'>
                {props.inSale && props.status === 1 && props.disabled &&
                  <View className='next buy-btn' onClick={props.onGroupBuy}>
                    <View className='top'>{props.zeroBuy != 1 ? '抢购' : '免费领取'}</View>
                    {process.env.DISTINGUISH_IDENTITY && !!props.commissionPrice &&
                      <View className='bottom'>购买返<Text className='dollar'>￥</Text><Text
                        className='true-price'
                      >{props.commissionPrice}</Text></View>}
                  </View>}
                {props.inSale && props.status === 1 && !props.disabled && <View className='next disabled buy-btn'>
                  <View className='top'>{props.zeroBuy != 1 ? '抢购' : '免费领取'}</View>
                  {process.env.DISTINGUISH_IDENTITY && !!props.commissionPrice &&
                    <View className='bottom'>购买返<Text className='dollar'>￥</Text><Text
                      className='true-price'
                    >{props.commissionPrice}</Text></View>}
                </View>}
                <View className='buy-btn' onClick={sureBtn.bind(this)}>下一步</View>
              </View>
            </View>
          </View>
        </Block>
      }
      {modalShow && <AtModal className='modal_concatWx' isOpened={Boolean(modalShow)} onClose={() => {
        setModalShow(false)
      }}
      >
        <AtModalHeader>{props.qrImgDescribe}</AtModalHeader>
        <AtModalContent>
          {props.qrImg && <Image
            style='width: 120px;height: 120px;'
            src={props.qrImg}
            mode='aspectFill'
          />}
        </AtModalContent>
        <AtModalAction>
          {process.env.TARO_ENV === 'h5' && <Text className='modal_txt'>
            有任何问题可添加<br />
            您的专属顾问进行咨询
          </Text>}
          {process.env.TARO_ENV !== 'h5' && <Text className='modal_txt'>
            有任何问题可添加\n
            您的专属顾问进行咨询
          </Text>}
        </AtModalAction>
      </AtModal>
      }
    </View>
  )
}

DetailBar.defaultProps = {
  showService: true,
  isLL: 0,
  showLoading: true,
  inSale: true,
  disabled: true,
  zeroBuy: 0,
  commissionPrice: 0,
  showWx: 0,
  subscribe: 0,
  isOpened: false,
  notOpen: false,
  groupDetail: false,
  oneMinute: false,
  wxModalShow: false
}

DetailBar.config = {
  usingComponents: process.env.TARO_ENV === 'tt' ? {
    'zijie-pay-button': '../../../components/pay-button/pay-button'
  } : {}
}

export default DetailBar
